<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="resetForm"
    :title="formData.id ? t('user.编辑用户') : t('user.新增用户')"
    width="600px"
    :confirmLoading="confirmLoading"
  >
    <el-form :model="formData" label-width="200px" ref="formRef" :rules="rules">
      <el-form-item :label="t('user.账号')" prop="username">
        <el-input v-model="formData.username" :disabled="!!formData.id" />
      </el-form-item>
      <el-form-item :label="t('user.姓名')" prop="nickName">
        <el-input v-model="formData.nickName" />
      </el-form-item>
      <el-form-item :label="t('user.性别')" prop="gender">
        <el-select v-model="formData.gender" :placeholder="t('user.请选择')">
          <el-option :label="t('user.男')" value="男" />
          <el-option :label="t('user.女')" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('user.手机号')" prop="phone">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item :label="t('user.身份证号')" prop="identityNo">
        <el-input v-model="formData.identityNo" />
      </el-form-item>
      <el-form-item :label="t('user.邮箱')" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item :label="t('user.权限组')" prop="roles">
        <el-select
          v-model="formData.roles"
          multiple
          :placeholder="t('user.请选择权限组')"
          value-key="id"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item['name' + locale]"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('user.状态')" prop="enabled">
        <el-switch v-model="formData.enabled" />
      </el-form-item>
      <el-form-item v-if="!formData.id" :label="t('user.登录密码')" prop="password">
        <el-input type="password" v-model="formData.password" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup>
import { ref, watch, onMounted, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";

const { t, locale } = useI18n();

const show = defineModel();
const emit = defineEmits(["success"]);
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 角色选项
const roleOptions = ref([]);
const confirmLoading = ref(false)

// 获取所有角色
const getRoles = async () => {
  try {
    const res = await Api.getRoleList({});
    if (res.status === 200) {
      roleOptions.value = res.data || [];
    }
  } catch (error) {
    console.error(t('user.获取角色列表失败'), error);
  }
};

watch(show, (val) => {
  if (val) {
    if (props.data && props.data.id) {
      formData.value = JSON.parse(JSON.stringify(props.data));
    } else {
      nextTick(()=>{
        resetForm();
      })
    }
  }
});

const formData = ref({
  id: "",
  username: "",
  nickName: "",
  gender: "男",
  phone: "",
  identityNo: "",
  email: "",
  roles: [],
  enabled: true,
  password: "",
});

const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }
  const pattern = /^1[3-9]\d{9}$/;
  if (!pattern.test(value)) {
    callback(new Error(t('user.请输入正确的手机号码')));
  } else {
    callback();
  }
};

const validateEmail = (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }
  const pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!pattern.test(value)) {
    callback(new Error(t('user.请输入正确的邮箱地址')));
  } else {
    callback();
  }
};

const rules = ref({
  username: [{ required: true, message: t('user.请输入账号'), trigger: "blur" }],
  nickName: [{ required: true, message: t('user.请输入姓名'), trigger: "blur" }],
  gender: [{ required: true, message: t('user.请选择性别'), trigger: "change" }],
  phone: [
    { required: true, message: t('user.请输入手机号码'), trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  email: [
    { validator: validateEmail, trigger: "blur" },
    { required: true, message: t('user.请输入邮箱'), trigger: "blur" },
  ],
  roles: [{ required: true, message: t('user.请选择权限组'), trigger: "change" }],
  password: [{ required: true, message: t('user.请输入登录密码'), trigger: "blur" }],
});

const formRef = ref();

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理角色数据格式
        const submitData = {
          ...formData.value,
          roles: formData.value.roles.map((role) => ({ id: role.id })),
        };
        const { id } = formData.value;
        confirmLoading.value = true
        const res = await Api[id ? "users_update" : "users_add"](submitData);
        if (res.status === 200) {
          ElMessage.success(`${id ? t('user.编辑成功') : t('user.新增成功')}`);
          emit("success");
          resetForm();
          show.value = false;
        }
        confirmLoading.value = false
      } catch (error) {
        ElMessage.error(`${id ? t('user.编辑失败') : t('user.新增失败')}`);
        console.error(error);
        confirmLoading.value = false
      }
    }
  });
};

const resetForm = () => {
  formData.value = {
    id: "",
    username: "",
    nickName: "",
    gender: "男",
    phone: "",
    identityNo: "",
    email: "",
    roles: [],
    enabled: true,
    password: "",
  };
  formRef.value.resetFields();
};

onMounted(() => {
  getRoles();
});
</script>
